<?php
namespace app\circle\controller\admin;

use app\circle\controller\admin\BaseController;
use app\circle\model\ClassModel;
use think\Request;

class ClassController extends BaseController
{
    protected $classModel;
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->classModel=new ClassModel();
    }

    public function index()
    {
        $searchText=$this->request->param('searchText','');
        $map=[];
        $query=[];
        if(!empty($searchText)){
            $map['class_name'] = ['like','%'.$searchText.'%'];
            $query['searchText'] = $searchText;
        }
        $list=$this->classModel->where($map)->paginate(15,false,['query'=>$query]);
        $this->assign('list',$list);
        $this->assign('query',$query);
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()){
            $data=$this->request->param();
            $result=$this->validate($data,[
                'class_name|部门名称' => 'require',
            ]);
            if (true!==$result){
                $this->error($result);
            }
            if ($this->classModel->addData($data)){
                $this->success('分类添加成功','index');
            }else{
                $this->error('分类添加失败');
            }
        }
        return $this->fetch();
    }

    public function edit()
    {
        $classId=$this->request->param('class_id',0);
        if ($this->request->isPost()){
            $data=$this->request->param();
            $result=$this->validate($data,[
                'class_name|部门名称' => 'require',
            ]);
            if (true!==$result){
                $this->error($result);
            }
            if ($this->classModel->editData($data)){
                $this->success('部门修改成功','index');
            }else{
                $this->error('部门修改失败');
            }
        }
        $info = $this->classModel->where('class_id',$classId)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }


    public function del()
    {
        $classId=$this->request->param('class_id',0);
        if ($this->classModel->destroy($classId)){
            $this->success('删除成功','index');
        }else{
            $this->error('删除失败','index');
        }
    }

    /**
     *分类排序
     */
    public function updateOrder()
    {
        $listOrder = $this->request->param('list_order/a');
        foreach ($listOrder as  $classId=> $classSort) {
            $classId    = intval($classId);
            $classSort   = intval($classSort);
            $dataList[] = ["class_id" => $classId, "class_sort" => $classSort];
        }
        $this->classModel->saveAll($dataList);
        $this->success('排序成功！');
    }
}